package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.car.MainTainData;
import com.gongpingjialoan.bean.car.MainTainItem;
import com.gongpingjialoan.bean.car.MyCarBean;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.ModifyMileBoardCast;
import com.gongpingjialoan.utility.BaseViewHolder;
import com.gongpingjialoan.widget.LoadingDialog;
import com.gongpingjialoan.widget.ModifyMileDialog;

import org.json.JSONObject;

import java.util.List;

/**
 * Created by Administrator on 2015/11/4.
 */
public class MainTainActivity extends BaseActivity implements OnClickListener, AdapterView.OnItemClickListener, ModifyMileBoardCast.IModifyMile {

    private static final int RESULT_LOGIN = 0x987;

    private MyCarBean myCarBean;

    private MainTainData mainTainData;

    private ImageView logo, brandLogo;

    private TextView juliTextView, brandTextView, modelTextView, mileTextView, maintainMileTextView, titleView, moneyTextView;

    private RelativeLayout popupRelativeLayout;

    private PopupWindow popupWindow;

    private ListView listView;

    private LinearLayout cailiaoLinearLayout, mainLinearLayout, needLinearLayout, priceLinearLayout;

    private int current = 0;


    private static final int APPIONT_TYPE = 0x0123;

    private static final int ALREADY_TYPE = 0x0124;

    private ImageView arrowImageView;

    private ModifyMileBoardCast modifyMileBoardCast;

    private LoadingDialog loadingDialog;

    private View popupView;

    private SpAdapter spAdapter;

    private NetDataJson netDataJson;

    private NetDataJson appiontNetDataJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maintain_layout_activity);
        setTitle("维修保养");
        initView();
        initData();
        registerBoardcast();
    }


    public void registerBoardcast() {
        modifyMileBoardCast = new ModifyMileBoardCast();
        modifyMileBoardCast.setiModifyMile(this);
        IntentFilter intentFilter = new IntentFilter(ModifyMileBoardCast.MODIFY_MILE_ACTION);
        registerReceiver(modifyMileBoardCast, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (modifyMileBoardCast != null) {
            unregisterReceiver(modifyMileBoardCast);
            modifyMileBoardCast = null;
        }
        if (netDataJson != null) {
            netDataJson.cancelTask();
            netDataJson = null;
        }
        if (appiontNetDataJson != null) {
            appiontNetDataJson.cancelTask();
            appiontNetDataJson = null;
        }
    }


    private void initView() {
        myCarBean = (MyCarBean) getIntent().getSerializableExtra("carbean");
        mainTainData = (MainTainData) getIntent().getSerializableExtra("maintain");
        loadingDialog = new LoadingDialog(this);
        priceLinearLayout = (LinearLayout) this.findViewById(R.id.main_layout_price);
        //initpopup
        popupView = LayoutInflater.from(this).inflate(R.layout.maintain_popup, null);
        listView = (ListView) popupView.findViewById(R.id.list);
        listView.setOnItemClickListener(this);
        spAdapter = new SpAdapter();
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ColorDrawable cd = new ColorDrawable(0x000000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                arrowImageView.setImageResource(R.drawable.icon_down);
            }
        });

        needLinearLayout = (LinearLayout) this.findViewById(R.id.need_linear);
        juliTextView = (TextView) this.findViewById(R.id.juli_id);
        moneyTextView = (TextView) this.findViewById(R.id.money_view);
        mainLinearLayout = (LinearLayout) this.findViewById(R.id.main_view);
        arrowImageView = (ImageView) this.findViewById(R.id.sp_icon);
        cailiaoLinearLayout = (LinearLayout) this.findViewById(R.id.cailiao_id);


        logo = (ImageView) this.findViewById(R.id.logo);
        brandLogo = (ImageView) this.findViewById(R.id.brandLogo);
        brandTextView = (TextView) this.findViewById(R.id.brand_id);
        modelTextView = (TextView) this.findViewById(R.id.model_id);
        mileTextView = (TextView) this.findViewById(R.id.mile_id);
        titleView = (TextView) this.findViewById(R.id.title_id);
        maintainMileTextView = (TextView) this.findViewById(R.id.maintain_mile_id);
        popupRelativeLayout = (RelativeLayout) this.findViewById(R.id.popup);
        popupRelativeLayout.setOnClickListener(this);

    }


    private void initData() {
        needLinearLayout.setVisibility(View.VISIBLE);
        if (mainTainData.getNext().isNeed_maintain_immediately()) {
//            needLinearLayout.setVisibility(View.VISIBLE);
            juliTextView.setVisibility(View.GONE);
            maintainMileTextView.setText("您的爱车需要一次保养");
        } else {
            maintainMileTextView.setText(mainTainData.getNext().getKilometers() + "公里");
//            needLinearLayout.setVisibility(View.GONE);
        }
        listView.setAdapter(spAdapter);


        ImageLoad.LoadImage(logo, myCarBean.getThumbnail(), R.drawable.car_loading,R.drawable.car_loading, MainTainActivity.this);
        ImageLoad.LoadImage(brandLogo, myCarBean.getBrand_log(), R.drawable.brandnull,R.drawable.brandnull, MainTainActivity.this);

//        Glide.with(this).load(myCarBean.getThumbnail()).placeholder(R.drawable.car_loading).into(logo);
//        Glide.with(this).load( myCarBean.getBrand_log()).placeholder(R.drawable.brandnull).error(R.drawable.brandnull).into(brandLogo);


        brandTextView.setText(myCarBean.getModel_zh());
        modelTextView.setText(myCarBean.getModel_detail_zh());
        int mile = (int) (Float.parseFloat(myCarBean.getMile()) * 10000);
        mileTextView.setText(mile + "公里");

        addmaterial(current);
    }


    /**
     * 保险所需要的材料
     */
    private void addmaterial(int position) {
        cailiaoLinearLayout.removeAllViews();
        List<MainTainItem> mainTainItems = mainTainData.getMaintain().get(position).getProjects();
        int size = mainTainItems.size();
        for (int i = 0; i < size; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.material_item, null);
            TextView textView = (TextView) view.findViewById(R.id.materical_text);
            textView.setText(mainTainItems.get(i).getName());
            cailiaoLinearLayout.addView(view, i);
        }
        titleView.setText(mainTainData.getMaintain().get(current).getTitle());
        if (mainTainData.getMaintain().get(position).getPrice() == 0) {
            priceLinearLayout.setVisibility(View.INVISIBLE);
        } else {
            moneyTextView.setText(mainTainData.getMaintain().get(position).getPrice() + "");
            priceLinearLayout.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 修改里程数
     *
     * @param v
     */
    public void modify_mile(View v) {
        ModifyMileDialog modifyMileDialog = new ModifyMileDialog(this, mainTainData.getNext().getMax_kilometers(), this, 1);
        modifyMileDialog.show();
    }


    //已做保养点击事件
    public void manageCar(View v) {
        ModifyMileDialog modifyMileDialog = new ModifyMileDialog(this, mainTainData.getNext().getMax_kilometers(), this, 2);
        modifyMileDialog.show();
    }

    //已做保养
    public void havdMaintain(final String type, final String mile) {
        final int s_mile = (int) (Double.parseDouble(mile) * 10000);
        if (netDataJson == null) {
            netDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loadingDialog.dismiss();
                    showTips(1, errorMessage);
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    loadingDialog.dismiss();
                    needLinearLayout.setVisibility(View.GONE);


                    Intent intent = new Intent(MainTainActivity.this, AddRecordMaintainActivity.class);
                    intent.putExtra("carbean", myCarBean);
                    intent.putExtra("type", type);
                    intent.putExtra("mile", s_mile + "");
                    startActivityForResult(intent, ALREADY_TYPE);

                    //刷新
                    if (MainActivity.main != null)
                        MainActivity.main.mUserHomeFragment.refresh();

                    Intent boardcastIntent = new Intent(ModifyMileBoardCast.MODIFY_MILE_ACTION);
                    boardcastIntent.putExtra("action" , "refresh");
                    sendBroadcast(boardcastIntent);
                }
            });
        }
        loadingDialog.show();
        netDataJson.setUrl(API.maintain_addrecord);

        netDataJson.addParam("kilometers", s_mile);
        netDataJson.addParam("mycar_id", myCarBean.getId());
        // netDataJson.addParam("type", type);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
        //  showTips(1 , type+mile);

    }


    public void modifyMile(String mile) {
        loadingDialog.show();
        Intent intent = new Intent(ModifyMileBoardCast.MODIFY_MILE_ACTION);
        intent.putExtra("action" , "action");
        intent.putExtra("mile" , mile);
        sendBroadcast(intent);
    }


    /**
     * 预约
     *
     * @param v
     */
    public void appiont_click(View v) {
        if (GPJApplication.getInstance().isLogin()) {
            appiontMaintain();
        } else {
            // 没有登陆
            Intent it = new Intent(this, LoginActivity.class);
            startActivityForResult(it, RESULT_LOGIN);
        }

    }

    private void appiontMaintain() {
        if (appiontNetDataJson == null) {
            appiontNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loadingDialog.dismiss();
                    showTips(1, errorMessage);
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    loadingDialog.dismiss();
                    Intent intent = new Intent(MainTainActivity.this, MainTainSuccessActivity.class);
                    intent.putExtra("maintainbean", mainTainData.getMaintain().get(current));
                    startActivityForResult(intent, APPIONT_TYPE);
                }
            });
        }
        loadingDialog.show();
        appiontNetDataJson.setUrl(API.appiont_maintain);
        appiontNetDataJson.setUseOtherDomain(true);
        appiontNetDataJson.addParam("title", mainTainData.getMaintain().get(current).getTitle());
        appiontNetDataJson.addParam("projects", getProjectData(mainTainData.getMaintain().get(current).getProjects()));
        appiontNetDataJson.addParam("price ", mainTainData.getMaintain().get(current).getPrice());
        appiontNetDataJson.addParam("mycar_id", myCarBean.getId());
        appiontNetDataJson.request("get");

    }


    private String getProjectData(List<MainTainItem> tainItems) {
        StringBuilder sb = new StringBuilder();
        int size = tainItems.size();
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                sb.append(tainItems.get(i).getName());
            } else {
                sb.append(tainItems.get(i).getName()).append(",");
            }
        }
        return sb.toString();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RESULT_LOGIN:
                    appiontMaintain();
                    break;
                case ALREADY_TYPE:
                case APPIONT_TYPE:
                    finish();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == popupRelativeLayout) {
            arrowImageView.setImageResource(R.drawable.icon_up);
            popupWindow.showAsDropDown(popupRelativeLayout, 0, 10);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        popupWindow.dismiss();
        if (current == position) {
            return;
        }
        current = position;
        addmaterial(current);
    }

    @Override
    public void modifySuccess(Intent intent) {
        loadingDialog.dismiss();
        String msg = intent.getStringExtra("msg");
        if ("success".equals(msg)) {
            myCarBean = (MyCarBean) intent.getSerializableExtra("carbean");
            mainTainData = (MainTainData) intent.getSerializableExtra("maintain");
            initData();
        } else {
            // showTips(1, msg);
        }
    }


    private class SpAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mainTainData.getMaintain().size();
        }

        @Override
        public Object getItem(int position) {
            return mainTainData.getMaintain().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(MainTainActivity.this).inflate(R.layout.sp_maintain_item, null);
            }
            TextView textView = BaseViewHolder.get(convertView, R.id.title);
            String title = mainTainData.getMaintain().get(position).getTitle();
            textView.setText(title);
            return convertView;
        }
    }


}
